package com.safx.selenium;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

import com.safx.entity.constants.EvalJS;
import com.safx.entity.constants.Xpath;
import com.safx.entity.enums.ResultEnum;
import com.safx.entity.env.MailEntity;
import com.safx.entity.env.SheduleEntity;
import com.safx.entity.env.VariableMap;
import com.safx.mail.ReceiveEmailHelper;
//import com.safx.entity.MailEntity;
//import com.safx.entity.SheduleEntity;
//import com.safx.entity.VariableMap;
//import com.safx.mail.ReceiveEmailHelper;

import com.safx.utility.CommonTool;
import com.safx.utility.DataProviderTool;

/**
 * 
 * <b> </b>
 * 
 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
 */
public class FunctionXmlDriveSelenium extends XmlDriveSelenium {

	// 单例模式
	private static FunctionXmlDriveSelenium funXMLDriveSelenium = null;

	private FunctionXmlDriveSelenium() {

	}

	/**
	 * 
	 * <b> 单例模式初始化</b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	// singleton
	public static FunctionXmlDriveSelenium getInstance() {
		if (null == funXMLDriveSelenium) {
			funXMLDriveSelenium = new FunctionXmlDriveSelenium();
		}
		return funXMLDriveSelenium;
	}

	/**
	 * 
	 * <b>dlink 网站的语言设置，并且通过javascript获得浏览器具体版本号（IE除外）和操作系统类型（不能区别32bit和64bit）
	 * </b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	public String setLanguage() {
		if (environment.getConfig().getOs() == null) {
			environment.getConfig().setOs(getEval(EvalJS.EVALGETOSJS));
			// logger.info("browser info: " + getEval(EvalJS.JQUERYJS));
		}
		if (environment.getConfig().getBrowser().contains("*")) {
			environment.getConfig().setBrowser(getEval(EvalJS.EVALGETBROWSERJS));
		}
		open("/signout");
		return open("/entrance?lang=" + environment.getConfig().getLanguage());
	}

	/**
	 * 
	 * <b> 获得device连接，超出时间就返回超时信息</b> R.表示可以retry，E。表示不需要retry
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	public String getConnectionType(String time) {
		String thisConnType = "R.";
		for (int looptimes = 0; looptimes < environment.getConfig().getRetryTimes() && thisConnType.contains("R."); looptimes++) {
			thisConnType = getConnectionType(CommonTool.String2Int(time));
			if (looptimes + 1 < environment.getConfig().getRetryTimes() && thisConnType.contains("R.")) {
				runScriptV2(EvalJS.SKIPFIRMWAREJS);
				logger.info("waitForLiveView: retry");
			}
		}
		return thisConnType;

	}

	/**
	 * 
	 * <b> 获得所有设备的链接方式</b><br/>
	 * 
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-7-4
	 */
	public String getAllConnectionType(String time) {
		String returnStr = "";
		String[] sns = getAllDeviceSNs().split(",");
		if (sns.length < 1) {
			return "have no device.";
		} else {
			for (int i = 0; i < sns.length; i++) {
				selectDevice(sns[i]);
				returnStr += sns[i] + ": " + getConnectionType(time) + "<br/>";
			}
			return returnStr;
		}
	}

	/**
	 * 
	 * <b> </b><br/>
	 * 获得页面上所有设备的八位码<br/>
	 * 12345678,78451278,89562356
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-7-4
	 */
	protected String getAllDeviceSNs() {
		int numb = CommonTool.String2Int(getEval("window.jQuery('tr[id]').length"));
		String returnStr = "";
		String temp = "device_list_";
		for (int i = 0; i < numb; i++) {
			// device_list_30035033
			temp = getEval("window.jQuery('tr[id]')[" + i + "].id");
			if (temp.contains("device_list_")) {
				returnStr += temp.replace("device_list_", "") + ",";
			}
		}
		if (returnStr.endsWith(",")) {
			returnStr = returnStr.substring(0, returnStr.length() - 1);
		}
		return returnStr;
	}

	/**
	 * 
	 * <b> 获得连接方式</b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	protected String getConnectionType(int timer) {
		sleep(5000);
		String info = "";
		SheduleEntity entity = new SheduleEntity(timer);
		iAmShedule(entity);
		int tempTime = 3000;
		while (!entity.isTimeout()) {
			sleep(tempTime);
			info = getEval(EvalJS.CONNECTIONINFOJS);
			if (null != ConnectionType(info)) {
				executor.shutdownNow();
				return ConnectionType(info);
			} else {
				// System.out.println(info);
			}
		}
		return "R. wait for live view " + environment.getConfig().getRetryTimes() + " time(s) timeout! ";
	}

	/**
	 * 
	 * <b> 获得连接方式</b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	protected String ConnectionType(String info) {
		if (isVisibleV2(Xpath.FW_TITLE)) {
			// runScriptV2(EvalJS.SKIPFIRMWAREJS);
			click(Xpath.FW_BUTTON);
		} else if (isVisibleV2(Xpath.CONNECTION_ERROR)) {
			return "R. Unable to access your camera's Live Video.";
		} else if (isVisibleV2(Xpath.OFFLINE)) {
			return "E. Your camera is offline.";
		}
		info = info.split("newLine")[(info.split("newLine").length) - 1];
		if (info.contains("$mDconnector:connected")) {
			if (info.contains("$mDconnector:connected[local]")) {
				return "Direct";
			} else if (info.contains("$mDconnector:connected[upnp]")) {
				return "Port";
			} else if (info.contains("$mDconnector:connected[stunt]")) {
				return "Relay";
			} else if (info.contains("$mDconnector:connected[relay]")) {
				return "Relay";
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 选择设备
	 * 
	 * @param SNValue
	 * @return
	 */
	public String selectDevice(String SNValue) {
		// for (int i = 0; i < 20; i++) {
		// sleep(3000);
		// // 正常可以选择设备||升级页面||Offline
		// if (isVisibleV2(Xpath.PWD_VERIFICATION) ||
		// isVisibleV2(Xpath.MYDLINK_TABBOX) || isVisibleV2(Xpath.FW_TITLE) ||
		// isVisibleV2(Xpath.OFFLINE)) {
		// break;
		// }
		// }
		// 清除控制台信息
		getEvalV2(EvalJS.CLEANCONNECTIONINFOJS);
		// 选择设备
		// runScriptV2("select_device(" + SNValue + ")");
		open("/device#" + SNValue);
		return "" + ResultEnum.PASS;
	}

	/**
	 * 等待LIVEVIEW页面出现
	 * 
	 * @param time
	 * @return
	 */
	public String waitForLiveView(String time) {
		String thisConnType = "R.";
		for (int looptimes = 0; looptimes < environment.getConfig().getRetryTimes() && thisConnType.contains("R."); looptimes++) {
			thisConnType = getConnectionType(CommonTool.String2Int(time));
			if (looptimes + 1 < environment.getConfig().getRetryTimes() && thisConnType.contains("R.")) {
				runScriptV2(EvalJS.SKIPFIRMWAREJS);
				logger.info("waitForLiveView: retry");
			}
		}
		if (thisConnType.contains("R.") || thisConnType.contains("E.")) {
			return "" + ResultEnum.PASS;
		} else {
			return "" + ResultEnum.PASS + ": " + thisConnType;
		}
	}

	/**
	 * 
	 * <b> 把email的信息放置到map里边</b>
	 * 
	 * @throws MessagingException
	 * @throws NoSuchProviderException
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-27
	 */
	public String getEmailInfo(String accountName) throws NoSuchProviderException, MessagingException {
		String subject = DataProviderTool.getData("email(" + accountName + ").subject");
		MailEntity f = ReceiveEmailHelper.getFirstMailBySubject(DataProviderTool.getData("account(" + accountName + ").email"), DataProviderTool.getData("account(" + accountName + ").emailPwd"), true, subject, true);
		if (f == null) {
			return "" + ResultEnum.FAIL + ": email with the subject '" + subject + "' is null.";
		} else {
			VariableMap map = VariableMap.getInstance();
			map.mapPutKV("contentText", f.getContentText());
			map.mapPutKV("link", f.getFirstLinksContent());
			map.mapPutKV("mailFromPersonal", f.getFrom().split(",")[0]);
			map.mapPutKV("mailFrom", f.getFrom().split(",")[1]);
			map.mapPutKV("from", f.getFrom());
			map.mapPutKV("mailTo", f.getMailTo());
			map.mapPutKV("subject", f.getSubject());
			map.mapPutKV("sendDate", f.getSentDate());
			map.mapPutKV("fromPersonal", f.getFromPersonal());
			map.mapPutKV("newPassword", f.getRedContent());
			return "" + ResultEnum.PASS;
		}
	}

	/**
	 * 
	 * <b> 打开device后台页面</b><br/>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-7-14
	 */
	public String openDevicePage(String sn, String tag) {
		if (tag.toLowerCase().contains("settings")) {
			// http://qa3.mydlink.com
			openWindow(environment.getConfig().getBaseUrl().replace("http://", "http://" + sn + ".") + "/?settings");
		} else {
			openWindow(environment.getConfig().getBaseUrl().replace("http://", "http://" + sn + ".") + "/?maintenance");
		}
		return "" + ResultEnum.PASS;
	}
	
	/**
	 * <b> Open Home page</b><br/>
	 * @author qiu.lin@hisoft.com
	 */
	public String openHomePage() {
		open(environment.getConfig().getBaseUrl());
		return "" + ResultEnum.PASS;
	}
}
